package cn.tedu.tmall.passport.service.impl;

import cn.tedu.tamll.common.enumerator.ServiceCode;
import cn.tedu.tamll.common.ex.ServiceException;
import cn.tedu.tamll.common.util.JwtUtils;
import cn.tedu.tmall.passport.dao.repository.IUserCacheRepository;
import cn.tedu.tmall.passport.dao.repository.IUserRepository;
import cn.tedu.tmall.passport.pojo.parm.UserLoginParam;
import cn.tedu.tamll.common.pojo.po.PermissionPO;
import cn.tedu.tamll.common.pojo.po.UserCachePO;
import cn.tedu.tamll.common.pojo.po.UserPO;
import cn.tedu.tmall.passport.pojo.po.vo.UserLoginVO;
import cn.tedu.tmall.passport.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserService implements IUserService {
    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private IUserCacheRepository userCacheRepository;
    private String secretKey = "fdsfads0000dxcfdfds3fsdfdsfdsfdsf";
    @Override
    public UserLoginVO login(UserLoginParam userLoginParam, HttpServletRequest httpServletRequest) {
        //验证用户名
        String username = userLoginParam.getUsername();
        //UserPO realUserPO = userRepository.getUserInfoByUsername(username);
        // System.out.println(realUserPO);
        UserPO userPO = new UserPO();
        userPO.setEnable(1);
        userPO.setId(1L);
        userPO.setUsername("llx");
        if (userPO == null) {
            throw new ServiceException(ServiceCode.ERR_JWT_EXPIRED, "用户名或密码错误");
        }
        String password = userLoginParam.getPassword();
        //获得该用户的全部权限
            List<PermissionPO> permissionPOS = userRepository.getAllPermissions(userPO.getId());
        //存入用户缓存
        UserCachePO userCachePO = new UserCachePO();
        userCachePO.setUserId(userPO.getId());
        userCachePO.setEnable(userPO.getEnable());
        userCachePO.setPermissions(permissionPOS);
        //保存到redis
        userCacheRepository.save(userCachePO);
        if (!userPO.getEnable().equals(1)) {
            throw new ServiceException(ServiceCode.ERR_JWT_EXPIRED, "登录失败,账号被禁用");
        }
        Map<String, Object> userData = new HashMap<>();
        userData.put("id", userPO.getId());
        userData.put("name", userPO.getUsername());
        String jwt = JwtUtils.generate(userData, secretKey);
        log.debug("jwt:{}", jwt);
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(1L);
        userLoginVO.setToken(jwt);
        userLoginVO.setUsername("llx");

        return userLoginVO;
    }


}
